export default {
  async fetch(request, env, ctx) {
    // 验证请求方法是否为 POST
    if (request.method !== "POST") {
      return new Response("Method not allowed", { status: 405 });
    }

    // 解析请求的 JSON 数据
    const update = await request.json();

    console.log("update", update); // 用于调试

    // 处理新成员加入的事件
    if (update.chat_member) {
      const chatMemberUpdate = update.chat_member;
      const newMember = chatMemberUpdate.new_chat_member;

      console.log("新加入的用户：", newMember);

      // 新加入的用户 member
      if (
        newMember &&
        (newMember.status === "restricted" || newMember.status === "member") &&
        newMember.is_member
      ) {
        // const chatId = chatMemberUpdate.chat.id // 群聊 ID
        const chatId = -1002338178870; // 群聊 ID
        const userId = newMember.user.id; // 用户 ID
        const setWelcomUserId = `welcome-${userId}`;
        const nickName = `${newMember.user.first_name || ""} ${
          newMember.user.last_name || ""
        }`.trim(); // 用户昵称

        // 检查用户是否已在群中 - START
        const alreadyWelcomed = await env.WELCOME_CACHE.get(setWelcomUserId);
        console.log("用户是否存在", alreadyWelcomed);
        if (alreadyWelcomed)
          return new Response("Already welcomed", { status: 200 });
        // 检查用户是否已在群中 - END

        const isSubscribed = await checkUserSubscription(env, userId);

        console.log("用户是否已关注频道：", isSubscribed);

        // 如果用户已关注频道，发送欢迎消息并解除禁言
        if (isSubscribed) {
          await unbanUser(env, chatId, userId); // 解除禁言
          const welcomeMessage = `🎉欢迎 ${newMember.user.first_name} 加入${chatMemberUpdate.chat.title}🎉\n🚀 一键闪连，不限流量不限速，免费试用,支持多设备登录🚀\n👩人工客服24h在线, 不定期发放福利抽大奖👩`;
          await env.WELCOME_CACHE.put(setWelcomUserId, "true");
          await sendMessage(env, welcomeMessage, chatId); // 发送欢迎消息
        } else {
          await sendFollowChannelMsg(env, chatId, userId, nickName);
          await env.WELCOME_CACHE.put(setWelcomUserId, "true");
          await muteUser(env, chatId, userId);
        }
      }

      // 退群的用户
      if (newMember && !newMember.is_member) {
        const userId = newMember.user.id;
        const setWelcomUserId = `welcome-${userId}`;
        console.log("退出群组的用户id：", userId);
        // await env.USER_MESSAGES_PRO.delete(userId)
        // await env.USER_CLICK_BUTTON_PRO.delete(userId)
        await env.WELCOME_CACHE.delete(setWelcomUserId);
      }
    }

    // 处理用户的产品ID回复
    if (update.message && update.message.text) {
      const text = update.message.text.trim(); // 用户输入的产品ID
      const regex = /^ *[#＃]? *闪连 *(\d{8}) *$/;
      const match = text.match(regex); // 尝试匹配
      const messageId = update.message.message_id; // 消息id
      // const chatId = update.message.chat.id // 群id
      const chatId = -1002338178870; // 群id
      const userId = update.message.from.id; // 用户id
      const nickName = `${update.message.from.first_name || ""} ${
        update.message.from.last_name || ""
      }`.trim(); // 用户昵称

      // 检测链接消息并处理（仅对非管理员用户）1
      if (text && !(await isAdmin(env, chatId, userId))) {
        // 检测消息中是否包含链接
        const containsLink = checkForLinks(text);
        if (containsLink) {
          // 删除链接消息
          await deleteMessage(env, chatId, messageId);
          // 禁言用户
          await muteUser(env, chatId, userId);
          // 发送禁言提示消息
          await sendMuteNotification(env, chatId, userId, nickName);
          // 提前返回，不再处理后续逻辑
          return new Response("OK");
        }
      }

      if (text.startsWith("#闪连") || text.startsWith("闪连")) {
        if (match) {
          const productId = match[1].trim(); // 提取 8 位数字
          const firstName = update.message.from.first_name;
          // 异步调用程序的接口处理业务
          await handleProductId(
            env,
            userId,
            firstName,
            productId,
            chatId,
            messageId
          );
        } else {
          const text = "❗️8位数字账户格式不对，请重新输入";
          await sendSpecifyMessage(env, text, chatId, messageId);
        }
      }

      // 抽奖 - 消息监听
      if (text == "抽奖" || text == "#抽奖") {
        const nickName = `${update.message.from.first_name || ""} ${
          update.message.from.last_name || ""
        }`; // 昵称
        const messageId = update.message.message_id; // 消息id
        // console.log(`监听到抽奖消息：群组id：${chatId} - 消息id：${messageId}`)

        await handleLotteryUser(env, userId, nickName, chatId, messageId);
      }

      // 领奖 - 消息监听
      if (text == "领奖" || text == "#领奖") {
        const nickName = `${update.message.from.first_name || ""} ${
          update.message.from.last_name || ""
        }`; // 昵称
        // console.log(`监听到领奖消息：用户id：${userId}`)
        await handleCouponsTgUser(env, userId, nickName);
      }

      // 导航 - 消息监听
      if (text === "导航") {
        // && (await isAdmin(env, chatId, userId))
        const welcomeMessage = `🎉欢迎大家加入闪连VPN群组！🎉\n🚀 一键闪连，不限流量不限速，免费试用,支持多设备登录🚀\n👩人工客服24h在线, 不定期发放福利抽大奖👩`;
        await sendMessage(env, welcomeMessage, chatId); // 发送欢迎消息
      }
    }

    // 处理回调查询（callback_query），用户点击按钮时触发
    if (update.callback_query) {
      const message = update.callback_query.message;
      const data = update.callback_query.data;
      const userId = update.callback_query.from.id; // 获取点击按钮的用户 ID
      const username = update.callback_query.from.username; // 获取用户名
      // const chatId = message.chat.id // 获取群聊 ID
      const chatId = -1002338178870; // 获取群聊 ID

      const nickName = `${update.callback_query.from.first_name || ""} ${
        update.callback_query.from.last_name || ""
      }`.trim(); // 用户昵称
      const callbackQueryId = update.callback_query.id; // 获取回调查询 ID

      // 处理发送链接解除禁言按钮点击2
      if (data === "unmute_user") {
        const isAdminUser = await isAdmin(env, chatId, userId);

        if (isAdminUser) {
          // 从消息文本中提取被禁言用户ID
          const muteMessageText = message.text;
          // 正则表达式匹配用户id
          const mutedUserIdMatch = muteMessageText.match(/user\?id=(\d+)/);

          if (mutedUserIdMatch && mutedUserIdMatch[1]) {
            const mutedUserId = parseInt(mutedUserIdMatch[1]);
            console.log("提取到的用户ID:", mutedUserId); // 添加日志
            // 解除用户禁言
            await unbanUser(env, chatId, mutedUserId);
            // 发送成功提示
            await sendForbiddenMsg(
              env,
              callbackQueryId,
              "已成功解除该用户的禁言"
            );
            // 删除禁言通知消息
            await deleteMessage(env, chatId, message.message_id);
          } else {
            // 如果正则匹配失败，尝试从entities中获取用户ID
            if (message.entities && message.entities.length > 0) {
              const userEntity = message.entities.find(
                (entity) => entity.type === "text_mention"
              );
              if (userEntity && userEntity.user && userEntity.user.id) {
                const mutedUserId = userEntity.user.id;
                console.log("从entities提取到的用户ID:", mutedUserId);
                // 解除用户禁言
                await unbanUser(env, chatId, mutedUserId);
                // 发送成功提示
                await sendForbiddenMsg(
                  env,
                  callbackQueryId,
                  "已成功解除该用户的禁言"
                );
                // 删除禁言通知消息
                await deleteMessage(env, chatId, message.message_id);
              } else {
                await sendForbiddenMsg(
                  env,
                  callbackQueryId,
                  "无法识别被禁言用户"
                );
              }
            } else {
              await sendForbiddenMsg(
                env,
                callbackQueryId,
                "无法识别被禁言用户"
              );
            }
          }
        } else {
          // 非管理员点击
          await sendForbiddenMsg(env, callbackQueryId, "您没有权限执行此操作");
        }
        return new Response("OK");
      }

      // 在群里 @ 用户并回复消息
      await sendGroupReply(
        env,
        chatId,
        username,
        data,
        userId,
        nickName,
        callbackQueryId
      );
      await answerCallbackQuery(env, callbackQueryId);
    }

    return new Response("OK");
  },
};

// 检测消息中是否包含链接3
function checkForLinks(text) {
  // URL正则表达式，匹配http/https链接和常见域名格式
  const urlRegex =
    /(https?:\/\/[^\s]+)|(www\.[^\s]+)|([a-zA-Z0-9-]+\.[a-zA-Z]{2,}(\.[a-zA-Z]{2,})?)/gi;
  return urlRegex.test(text);
}

// 发送禁言通知消息4
async function sendMuteNotification(env, chatId, userId, nickName) {
  const TOKEN = "7223420659:AAEXFUKaR5sVP4b3LuEkbnFtmJzhXFb54go";
  const url = `https://api.telegram.org/bot${TOKEN}/sendMessage`;
  const keyboard = {
    inline_keyboard: [[{ text: "✅解除禁言", callback_data: "unmute_user" }]],
  };

  const response = await fetch(url, {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
    },
    body: JSON.stringify({
      chat_id: chatId,
      text: `⚠️ <a href="tg://user?id=${userId}">${nickName}</a> 因发送链接消息已被禁言。\n只有群主或管理员可以解除禁言。`,
      parse_mode: "HTML",
      reply_markup: {
        inline_keyboard: keyboard.inline_keyboard,
      },
    }),
  });

  return response.json();
}

// 检查用户是否为群主或管理员
async function isAdmin(env, chatId, userId) {
  const TOKEN = "7223420659:AAEXFUKaR5sVP4b3LuEkbnFtmJzhXFb54go";
  const url = `https://api.telegram.org/bot${TOKEN}/getChatMember?chat_id=${chatId}&user_id=${userId}`;

  try {
    const response = await fetch(url);
    const res = await response.json();
    const status = res.result.status;

    return ["administrator", "creator"].includes(status);
  } catch (error) {
    return false;
  }
}

// 验证用户是否关注频道
async function checkSubscription(
  env,
  chatId,
  username,
  data,
  userId,
  nickName,
  callbackQueryId
) {
  // 检查用户是否已关注频道
  const isSubscribed = await checkUserSubscription(env, userId);

  console.log("用户是否已关注频道：", isSubscribed);

  if (isSubscribed) {
    await unbanUser(env, chatId, userId); // 解除禁言
    await deleteAllMessage(env, chatId, userId); // 删除消息
    await sendForbiddenMsg(
      env,
      callbackQueryId,
      "您已关注频道，无需再次验证。"
    );
  } else {
    await muteUser(env, chatId, userId); // 禁言
    await sendForbiddenMsg(
      env,
      callbackQueryId,
      "您还未关注频道，请关注频道后再次验证。"
    );
  }
}

// 检查用户是否关注频道
async function checkUserSubscription(env, userId) {
  const TOKEN = "7223420659:AAEXFUKaR5sVP4b3LuEkbnFtmJzhXFb54go";
  const CHANNEL_USERNAME = "lightningxvpnnotification";
  const url = `https://api.telegram.org/bot${TOKEN}/getChatMember?chat_id=@${CHANNEL_USERNAME}&user_id=${userId}`;

  try {
    const response = await fetch(url);
    const res = await response.json();
    const status = res.result.status;

    console.log("检查用户是否关注频道结果：", res);

    // 如果用户的状态是 'member' 或 'administrator' 或 'creator'，说明用户已关注频道
    return ["member", "administrator", "creator"].includes(status);
  } catch (error) {
    console.error("检查用户订阅失败：", error);
    return false; // 如果调用失败，默认认为用户未关注
  }
}

// 禁言用户
async function muteUser(env, chatId, userId) {
  const TOKEN = "7223420659:AAEXFUKaR5sVP4b3LuEkbnFtmJzhXFb54go";
  const url = `https://api.telegram.org/bot${TOKEN}/restrictChatMember`;

  const response = await fetch(url, {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
    },
    body: JSON.stringify({
      chat_id: chatId,
      user_id: userId,
      permissions: {
        can_send_messages: false, // 允许发送消息
        can_send_media_messages: false, // 允许发送媒体消息
        can_send_polls: false, // 是否允许用户创建和发送民意调查
        can_send_other_messages: false, // 否允许用户发送其他类型的消息（例如贴纸、GIF、游戏）
        can_add_web_page_previews: false, // 是否允许用户添加网页预览到其消息中
        can_invite_users: false, // 允许邀请用户
      },
    }),
  });

  const result = await response.json();

  return result;
}

// 解除禁言
async function unbanUser(env, chatId, userId) {
  const TOKEN = "7223420659:AAEXFUKaR5sVP4b3LuEkbnFtmJzhXFb54go";
  const url = `https://api.telegram.org/bot${TOKEN}/restrictChatMember`;

  const response = await fetch(url, {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
    },
    body: JSON.stringify({
      chat_id: chatId,
      user_id: userId,
      permissions: {
        can_send_messages: true, // 允许发送消息
        can_send_media_messages: true, // 允许发送媒体消息
        can_send_polls: false, // 是否允许用户创建和发送民意调查
        can_send_other_messages: true, // 否允许用户发送其他类型的消息（例如贴纸、GIF、游戏）
        can_add_web_page_previews: false, // 是否允许用户添加网页预览到其消息中
        can_invite_users: true, // 允许邀请用户
      },
    }),
  });

  const result = await response.json();

  console.log("解除禁言结果：", result);

  return result;
}

// 存储要删除的用户消息id
async function pushMsgId(env, userId, messageId) {
  console.log("存储要删除的用户消息id和消息id", userId, messageId);
  await env.USER_MESSAGES_PRO.put(userId, messageId);
}

// 存储用户点击的按钮和点击时间
async function setClickBtnTime(env, userId, data, clickTime) {
  const userClickButton = (await env.USER_CLICK_BUTTON_PRO.get(userId)) || "[]";

  const parsedData = JSON.parse(userClickButton);
  const index = parsedData.findIndex((item) => item.btn === data);

  if (index > -1) {
    parsedData.splice(index, 1);
  }

  parsedData.push({ btn: data, clickTime });
  await env.USER_CLICK_BUTTON_PRO.put(userId, JSON.stringify(parsedData));
}

// 发送弹窗消息
async function sendForbiddenMsg(env, callbackQueryId, text) {
  const TOKEN = "7223420659:AAEXFUKaR5sVP4b3LuEkbnFtmJzhXFb54go";
  const url = `https://api.telegram.org/bot${TOKEN}/answerCallbackQuery`;

  const data = {
    callback_query_id: callbackQueryId,
    text: text,
    show_alert: false,
  };

  const response = await fetch(url, {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
    },
    body: JSON.stringify(data),
  });

  const result = await response.json();

  console.log("禁止点击按钮弹窗", result);

  return result;
}

// 删除所有相关频道相关消息
async function deleteAllMessage(env, chatId, userId) {
  const messageId = await env.USER_MESSAGES_PRO.get(userId);

  console.log("要删除的消息id", messageId);

  await deleteMessage(env, chatId, messageId);
  await env.USER_MESSAGES_PRO.delete(userId);
}

// 删除指定消息
async function deleteMessage(env, chatId, messageId) {
  const TOKEN = "7223420659:AAEXFUKaR5sVP4b3LuEkbnFtmJzhXFb54go";
  const url = `https://api.telegram.org/bot${TOKEN}/deleteMessage`;

  const response = await fetch(url, {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
    },
    body: JSON.stringify({
      chat_id: chatId,
      message_id: messageId, // 要删除的消息 ID
    }),
  });

  const result = await response.json();

  return result.ok; // 返回是否删除成功
}

// 处理抽奖消息请求
async function handleLotteryUser(env, userId, nickName, chatId, messageId) {
  const apiUrl = "https://api.shanlianvpn.info/app/rr/lotteryTg";

  try {
    // 使用 await 等待 fetch 完成，并捕获返回结果
    const response = await fetch(apiUrl, {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        Authorization: "Q59J0NoBZkYYhILi",
      },
      body: JSON.stringify({
        tgAccountId: userId,
        firstName: nickName,
      }),
    });

    // 检查响应是否成功
    if (!response.ok) {
      throw new Error(`HTTP error! Status: ${response.status}`);
    }

    // 获取响应体
    const responseData = await response.json();
    console.log("API response:", responseData);

    const { code, data, msg } = responseData;

    let text;

    switch (code) {
      case 200:
        text = `✅ 参与成功！\n今日参与人数：${data}人\n请耐心等待每日0点中奖名单公布！`;
        break;
      case -1:
        text = `❗请先绑定闪连数字账户\n绑定方法：\n在群内发送如下格式的消息即可完成绑定\n#闪连8位数字账户\n例如：#闪连80018001`;
        break;
      case -2:
        text = msg;
        break;
    }

    await sendSpecifyMessage(env, text, chatId, messageId); // 回复消息

    return data; // 返回结果供其他地方使用
  } catch (error) {
    console.error("Error sending product ID:", error); // 处理可能的错误
    return { error: "Failed to call API" }; // 返回错误消息
  }
}

// 回复群组中指定抽奖消息
async function sendSpecifyMessage(env, text, chatId, messageId) {
  const TOKEN = "7223420659:AAEXFUKaR5sVP4b3LuEkbnFtmJzhXFb54go";
  const url = `https://api.telegram.org/bot${TOKEN}/sendMessage`;

  const response = await fetch(url, {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
    },
    body: JSON.stringify({
      chat_id: chatId,
      text: text,
      reply_to_message_id: messageId, // 指定消息id
      parse_mode: "Markdown", // 或者 'HTML'
    }),
  });

  return response.json();
}

// 处理领奖消息请求
async function handleCouponsTgUser(env, userId, nickName) {
  const apiUrl = "https://api.shanlianvpn.info/app/rr/couponsTg";

  try {
    // 使用 await 等待 fetch 完成，并捕获返回结果
    const response = await fetch(apiUrl, {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        Authorization: "Q59J0NoBZkYYhILi",
      },
      body: JSON.stringify({
        tgAccountId: userId,
        firstName: nickName,
      }),
    });

    // 检查响应是否成功
    if (!response.ok) {
      throw new Error(`HTTP error! Status: ${response.status}`);
    }

    // 获取响应体
    const responseData = await response.json();
    console.log("API response:", responseData);

    const { code, data, msg } = responseData;

    let text;

    switch (code) {
      case 200:
        text = `兑换码: ${data}`;
        break;
      case -1:
        text = msg;
        break;
      case -2:
        text = msg;
        break;
    }

    await sendSingMessage(env, text, userId, code); // 回复消息

    return data; // 返回结果供其他地方使用
  } catch (error) {
    console.error("Error sending product ID:", error); // 处理可能的错误
    return { error: "Failed to call API" }; // 返回错误消息
  }
}

// 回复领奖消息
async function sendSingMessage(env, text, userId, code) {
  const TOKEN = "7223420659:AAEXFUKaR5sVP4b3LuEkbnFtmJzhXFb54go";
  let url;
  let data;

  switch (code) {
    case 200:
      url = `https://api.telegram.org/bot${TOKEN}/sendPhoto`;
      data = {
        chat_id: userId,
        photo: `https://shanlianvpn.info/notice/duihuan.png`,
        caption: text,
        parse_mode: "HTML",
      };
      break;

    default:
      url = `https://api.telegram.org/bot${TOKEN}/sendMessage`;
      data = {
        chat_id: userId,
        text: text,
        parse_mode: "Markdown", // 或 "HTML"，用于格式化消息
      };
      break;
  }

  const response = await fetch(url, {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
    },
    body: JSON.stringify(data),
  });

  return response.json();
}

// 发送消息的函数
async function sendMessage(env, text, chatId) {
  const TOKEN = "7223420659:AAEXFUKaR5sVP4b3LuEkbnFtmJzhXFb54go"; // 替换为你的 Bot Token
  const url = `https://api.telegram.org/bot${TOKEN}/sendMessage`;

  const keyboard = {
    inline_keyboard: [
      [
        { text: "官网下载", url: "https://lightningxvpn.com/cn/download" },
        { text: "备用官网地址", url: "https://unionbyte.online/cn" },
      ],
      [
        { text: "iOS如何安装", url: "https://lightningxvpn.com/cn/faq/?key=5" },
        {
          text: "iOS如何付费",
          url: "https://t.me/lightningxvpnnotification/33",
        },
      ],
      [
        {
          text: "推广赚钱",
          url: "https://lightningxvpn.com/cn/affiliate-program",
        },
        {
          text: "安卓版本无法付费？",
          url: "https://t.me/lightningxvpnnotification/33",
        },
      ],
      [
        { text: "商务合作", url: "https://t.me/LightningX_VPN" },
        {
          text: "抽奖领取VIP兑换码",
          url: "https://t.me/lightningxvpnnotification/27",
        },
      ],
      [
        {
          text: "绑定闪连帐号获取任务返现佣金",
          callback_data: "getAmountJoinTg",
        },
      ],
    ],
  };

  const response = await fetch(url, {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
    },
    body: JSON.stringify({
      chat_id: chatId, // 使用动态的 chatId
      text: text,
      reply_markup: keyboard,
    }),
  });

  return response.json();
}

// 发送关注频道消息
async function sendFollowChannelMsg(env, chatId, userId, nickName) {
  const TOKEN = "7223420659:AAEXFUKaR5sVP4b3LuEkbnFtmJzhXFb54go";
  const url = `https://api.telegram.org/bot${TOKEN}/sendMessage`;
  const keyboard = {
    inline_keyboard: [
      [
        { text: "📣关注频道", url: "https://t.me/lightningxvpnnotification" },
        { text: "✅我已关注", callback_data: "check_subscription" },
      ],
    ],
  };

  const response = await fetch(url, {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({
      chat_id: chatId,
      text: `<a href="tg://user?id=${userId}">${nickName}</a> 请点击下方按钮关注闪连VPN官方频道并完成验证后，即可发言。`,
      parse_mode: "HTML",
      reply_markup: { inline_keyboard: keyboard.inline_keyboard },
    }),
  });

  const result = await response.json();
  const messageId = result.result.message_id;

  await pushMsgId(env, userId, messageId);

  return result;
}

// 在群里 @ 用户并回复消息的函数
async function sendGroupReply(
  env,
  chatId,
  username,
  data,
  userId,
  nickName,
  callbackQueryId
) {
  const TOKEN = "7223420659:AAEXFUKaR5sVP4b3LuEkbnFtmJzhXFb54go"; // 替换为你的 Bot Token
  const url = `https://api.telegram.org/bot${TOKEN}/sendMessage`;

  const responseTextMap = {
    getAmountJoinTg: `💰在群内发送如下格式的消息即可完成绑定获得任务返现佣金💰\n#闪连8位数字账户\n例如：#闪连80018001 \n绑定结果将由机器人推送告知`,
  };

  // 非外链按钮
  switch (data) {
    case "check_subscription": // ✅我已关注
      return await checkSubscription(
        env,
        chatId,
        username,
        data,
        userId,
        nickName,
        callbackQueryId
      );
    case "getAmountJoinTg": // 绑定闪连帐号获取任务返现佣金
      const userClickButton = JSON.parse(
        (await env.USER_CLICK_BUTTON_PRO.get(userId)) || "[]"
      );
      const clickTime = userClickButton.find(
        (item) => item.btn === "getAmountJoinTg"
      )?.clickTime;

      // 间隔时间小于5分钟
      if (clickTime && Date.now() < clickTime + 5 * 60 * 1000) {
        return await sendForbiddenMsg(
          env,
          callbackQueryId,
          "点击太频繁了，请5分钟后再点击。"
        );
      } else {
        await setClickBtnTime(env, userId, data, Date.now());
      }
      break;
  }

  if (!data) return console.log("未匹配对应的按钮");

  const responseText = responseTextMap[data];

  const response = await fetch(url, {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
    },
    body: JSON.stringify({
      chat_id: chatId, // 在群里发送消息
      text: responseText,
      parse_mode: "HTML",
    }),
  });

  const result = await response.json();

  return result;
}

// 发送抽奖图文消息
async function sendPhotoTextMsg(env, chatId) {
  const TOKEN = "7223420659:AAEXFUKaR5sVP4b3LuEkbnFtmJzhXFb54go";
  const url = `https://api.telegram.org/bot${TOKEN}/sendPhoto`;

  const data = {
    chat_id: chatId,
    photo: `https://shanlianvpn.info/notice/choujiang.png`,
    caption: `参与方式：\n每日在群内发送 #抽奖  即可参与抽奖，每天3个中奖名额限量发放。\n\n中奖公布：\n每日0点在群内进行中奖名单公布！\n\n兑换方式:\n1.中奖者通过私聊 - <a href="https://t.me/lightningxvpn_bot">官方机器人</a>\n\n2.发送<blockquote>领奖</blockquote>即可获得 奖品兑换码及使用方法说明。`,
    parse_mode: "HTML",
  };

  const response = await fetch(url, {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
    },
    body: JSON.stringify(data),
  });

  return response.json();
}

// 回应 Telegram 服务器，表示 callback_query 已处理
async function answerCallbackQuery(env, callbackQueryId) {
  const TOKEN = "7223420659:AAEXFUKaR5sVP4b3LuEkbnFtmJzhXFb54go"; // 替换为你的 Bot Token
  const url = `https://api.telegram.org/bot${TOKEN}/answerCallbackQuery`;

  const response = await fetch(url, {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
    },
    body: JSON.stringify({
      callback_query_id: callbackQueryId,
    }),
  });

  return response.json();
}

// 处理产品ID并调用外部API
async function handleProductId(
  env,
  userId,
  firstName,
  userName,
  chatId,
  messageId
) {
  console.log(userId + "," + firstName + "," + userName);
  const apiUrl = "https://api.shanlianvpn.info/app/rr/jionTg";
  try {
    // 使用 await 等待 fetch 完成，并捕获返回结果
    const response = await fetch(apiUrl, {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        Authorization: "Q59J0NoBZkYYhILi",
      },
      body: JSON.stringify({
        tgAccountId: userId,
        firstName: firstName,
        userName: userName,
      }),
    });

    // 检查响应是否成功
    if (!response.ok) {
      throw new Error(`HTTP error! Status: ${response.status}`);
    }

    // 获取响应体
    const responseData = await response.json();

    const { code, data, msg } = responseData;
    let text;

    switch (code) {
      case 200:
        text = `绑定成功，返现佣金已发放至你的闪连账户`;
        break;
      case -1:
        text = `此Telegram账户已存在绑定关系`;
        break;
      case -2:
        text = "此闪连账户已存在绑定关系";
        break;
      case -3:
        text = "此闪连账户不存在";
        break;
      default:
        text = "未知错误";
    }

    await sendSpecifyMessage(env, text, chatId, messageId);

    return data; // 返回结果供其他地方使用
  } catch (error) {
    console.error("Error sending product ID:", error); // 处理可能的错误
    return { error: "Failed to call API" }; // 返回错误消息
  }
}
